<?php
// +----------------------------------------------------------------------
// | BhAdmin [ BhAdmin匠心打造，我们相信，每个伟大的软件都有一个伟大的故事 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2023 https://www.bhadmin.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BhAdmin并不是自由软件，未经许可不能去掉BhAdmin相关版权
// +----------------------------------------------------------------------
// | Author: BAIHU  <admin@bhadmin.cn>
// +----------------------------------------------------------------------
namespace app\admin\logic;

use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Service\CityService;

class CityLogic extends BackendLogic
{

    public function __construct()
    {
        $this->service = Container::get(CityService::class);
    }

    /**
     * 分页列表
     * @return array
     */
    public function getList(): array
    {
        $param = request()->all();

        $where = [];
        $where[] = ["mark", '=', 1];
        $pid = $param['pid'] ?? 0;
        $where[] = ["pid", '=', (int)$pid];
        if (!empty($param['name'])) {
            $where[] = ["name", 'like', "%{$param['name']}%"];
        }
        $list = $this->service->getList($where, ['*'], ['sort' => 'asc']);
        if (!$list) return message();
        foreach ($list as &$val) {
            if ($val['level'] <= 2) {
                $val['hasChildren'] = true;
            }
        }
        return message($list);
    }

    public function edit(): array
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;

        if (empty($data['pid'])) throw new ApiException('请选择上级');
        if (empty($data['name'])) throw new ApiException('请输入城市名称');
        if (empty($data['level'])) throw new ApiException('请选择城市等级');
        if (empty($data['citycode'])) throw new ApiException('请输入城市编码');

        $save['name'] = trim($data['name']);
        $save['pid'] = $data['pid'];
        $save['level'] = $data['level'];
        $save['citycode'] = $data['citycode'];
        $save['adcode'] = $data['adcode'] ?? '';
        $save['lat'] = $data['lat'] ?? '';
        $save['lng'] = $data['lng'] ?? '';
        $save['sort'] = $data['lng'] ?? '';
        unset($data['id']);
        if ($id == 0) {
            $count = $this->service->getUserCountByWhere([["citycode", '=', $save['citycode']], ["mark", "=", 1]]);
            if ($count > 0) throw new ApiException('系统中已存在相同的城市编码');
            $this->service->add($save);
        } else {
            $count = $this->service->getUserCountByWhere([["citycode", '=', $save['citycode']], ["id", "<>", $id], ["mark", "=", 1]]);
            if ($count > 0) throw new ApiException('系统中已存在相同的城市编码');
            $this->service->save($save, $id);
        }
        return message();

    }


}
